package com.knoya.chejian.pda.activity

import android.app.AlertDialog
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.ArrayAdapter
import android.widget.TextView
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import com.knoya.chejian.pda.R
import com.knoya.chejian.pda.contacts.Contacts
import com.knoya.chejian.pda.minterface.OnUserDataInterface
import com.knoya.chejian.pda.util.*
import com.knoya.chejian.pda.xieyi.PrivacyDialog
import kotlinx.android.synthetic.main.activity_login.*

import org.json.JSONObject
import org.xutils.http.cookie.DbCookieStore

class LoginActivity : BaseActivity(), TextView.OnEditorActionListener {

    private var name: String =""
    private var password: String =""
    private var child_name: String =""//输入的账号和密码子账号
    private var islogin = false//登录状态，true为已登录
    private var isxieyi = false;
    lateinit var updatedialog: AlertDialog
    private var country: List<String> = arrayListOf()


    private var lishiname: String = ""

    private var token = ""
    private var username = ""
    private var uid = ""
    private var mail = ""
    override fun getLayoutId(): Int {
        return R.layout.activity_login
    }

    override fun initCreate() {
        Log.d("TAAAG","+++++++++++++++++++++++")
        initView()//初始化控件
        initclick()//控件监听
        EtMainNumble.hint = "用户名/手机号"
        setupCountry()
        val filter = IntentFilter()
        filter.addAction(Contacts.BORADCAST_ACTION_DINGDING)//为BroadcastReceiver指定一个action，即要监听的消息名字
//        registerReceiver(mBoradcastReceiver, filter) //动态注册监听  静态的话 在AndroidManifest.xml中定义
        EtMainNumble.setOnEditorActionListener(this)
        EtPassword.setOnEditorActionListener(this)
        EtSonNumble.setOnEditorActionListener(this)
        var dialog = PrivacyDialog(this)
        isxieyi = sp.getBoolean("isxieyi", islogin)
        if(!isxieyi){
            dialog.showPrivacy(this,dialog,editor);
        }

    }

//    /**钉钉登录*/
//    private val mBoradcastReceiver = object : BroadcastReceiver() {
//        override fun onReceive(context: Context, intent: Intent) {
//            if (intent.action == Contacts.BORADCAST_ACTION_DINGDING) {//关闭app的广播
//                var auth_code = intent.getStringExtra("auth_code")
//                updatedialog = Myutil.showupdatedialog(this@LoginActivity, "正在登录", true)
//                Httputil.setDingDIng(this@LoginActivity,auth_code,object : OnUserDataInterface{
//                    override fun onUserData(data: String) {
//                        jsondata(data)
//                    }
//
//                    override fun onNot(throwable: String?) {
//                        updatedialog.dismiss()
//                    }
//
//                })
//            }
//        }
//    }

    private fun setupCountry() {
        country= Sputil.sp("name").getString("lishiname", "")!!.split(",")
        val av = ArrayAdapter(this,
            android.R.layout.simple_dropdown_item_1line, country)
        EtMainNumble.setAdapter(av)
        EtMainNumble.threshold = 1
    }

    //控件监听
    private fun initclick() {
//        TvDingDing.setOnClickListener {
//            sendAuth()
//        }
        CbSon.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                LlSon.visibility = View.VISIBLE
                EtMainNumble.hint = "主账号"
            } else {
                LlSon.visibility = View.GONE
                EtMainNumble.hint = "用户名/手机号"
                EtSonNumble.setText("")
            }
        }

        BtSingin.setOnClickListener {
            if (EtMainNumble.text.toString() != "" && EtPassword.text.toString() != "") {
                updatedialog = Myutil.showupdatedialog(this@LoginActivity, "正在登录", true)
                httplogin()
            } else {
                Myutil.MyTost("请输入用户名和密码")
            }
        }
        TvZhaoHui!!.setOnClickListener {
            //            val intent = Intent(this@LoginActivity, MiMaActivity::class.java)
//            startActivity(intent)
        }
    }

//    lateinit var iddShareApi: IDDShareApi
//    private fun sendAuth() {
//        iddShareApi = DDShareApiFactory.createDDShareApi(this, Contacts.APP_ID, true)
//        val req = SendAuth.Req()
//        req.scope = SendAuth.Req.SNS_LOGIN
//        req.state = "test"
//        if (req.supportVersion > iddShareApi.ddSupportAPI) {
//            httperrordiaog(this, "未安装钉钉或者钉钉版本过低，不支持登录授权")
//            return
//        }
//        iddShareApi.sendReq(req)
//    }

    //初始化控件
    private fun initView() {
        islogin = sp.getBoolean("islogin", islogin)
        metric()//获取屏幕属性并存储
    }

    //存储屏幕属性
    private fun metric() {
        val metric = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(metric)
        val width = metric.widthPixels     // 屏幕宽度（像素）
        val height = metric.heightPixels   // 屏幕高度（像素）
        val density = metric.density      // 屏幕密度（0.75 / 1.0 / 1.5）
        val densityDpi = metric.densityDpi  // 屏幕密度DPI（120 / 160 / 240）
        editor.putInt("width", width)
        editor.putInt("height", height)
        editor.commit()
    }

    //登录网络访问
    private fun httplogin() {
        name = EtMainNumble.text.toString().trim()
        password = EtPassword.text.toString().trim()
        child_name = EtSonNumble.text.toString().trim ()
        HttpUtil.setLogin(this, name, password, child_name, object : OnUserDataInterface {
            override fun onUserData(s: String) {
                jsondata(s)
            }

            override fun onNot(s: String) {
                updatedialog.dismiss()
                EtPassword.setText("")
            }
        })
    }

    fun jsondata(s : String){
        try {
            val jo = JSONObject(s)
            token = JsonUtil.getvolue(jo, "token")
            val session_name = JsonUtil.getvolue(jo, "session_name")
            val jouser = JsonUtil.getjovolue(jo, "user")
            if (jouser != null) {
                username = jouser.getString("name")
                mail = jouser.getString("mail")
                uid = jouser.getString("uid")
            }
            val instance = DbCookieStore.INSTANCE
            val cookies = instance.cookies
            for (i in cookies.indices) {
                val cookie = cookies[i]
                if (cookie.name == session_name) {
                    editor.putString("cookie", session_name + "=" + cookie.value)
                } else {
                    editor.putString("cookies", cookie.name + "=" + cookie.value)
                }
            }
            instance.removeAll()
            editor.putString("uid", uid)
            editor.putString("mail", mail)
            editor.putString("name", username)
            editor.putString("token", token)
            editor.putString("user", jouser!!.toString())
            editor.putBoolean("islogin", true)
            editor.commit()
        } catch (e: Exception) {
            Myutil.Mylog("TAAAAG", e.toString())
            e.printStackTrace()
        }

//        Httputil.setdeviceID(this@LoginActivity, Myapp.getpushService().deviceId, object : OnUserDataInterface {
//            override fun onUserData(data: String) {}
//
//            override fun onNot(throwable: String) {}
//        })
        val intent = Intent(this@LoginActivity, MainActivity::class.java)
        startActivity(intent)
        if (!isyou(name)) {
            if (lishiname == null) {
                lishiname = ""
            }
            Sputil.editor("name").putString("lishiname", lishiname + "," + name).commit()
        }
        finish()
    }

    private fun isyou(name: String?): Boolean {
        for (i in country.indices) {
            if (country[i] == name) {
                return true
            }
        }
        return false
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == 4) {
            finish()
        }
        return true
    }

    companion object {
        val TAG = "LoginActivity"
        private val a = "LoginActivity"
    }

    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        return true
    }


}
